import { parentPort, threadId } from 'worker_threads'

import matchRoute from './matchRoute'
import renderTag from './renderTag'
import renderHtml from './renderHtml'
import renderRoot from './renderRoot'
import configureStore from '../redux/configureStore'
import createReducer from '../redux/createReducer'
import PROJECT from '../PROJECT'

const { App, actions, routes } = require(PROJECT.BUILD.ROOT)
const rootReducer = createReducer(actions)

parentPort.on('message', msg => {
  // console.log(msg, 'threadId:', threadId)
  const req = msg.input
  const lang = req.query.lang || 'zh_CN'
  const store = configureStore(rootReducer, { lang })
  const context = {}
  const route = matchRoute(store, req, routes)

  Promise.all(route.tasks).then(() => {
    const extractor = renderTag()
    const content = renderRoot({ Component: App, url: req.originalUrl, context, store, extractor })
    const html = renderHtml({ content, state: store.getState(), entry: route.entry, extractor })
    parentPort.postMessage({ output: html, i: msg.i })
  }).catch(err => {
    parentPort.postMessage({ output: err, i: msg.i })
    console.log(err)
  })

})
